﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using CERT.Services.DAL;
using CERT.Services;
using System.Web.Mvc;


namespace CERT.Controllers
{
    public class TeamController : ApiController
    {
        private INETServices Service;


        public TeamController()
        {
            Service = new NETServices();

        }

        public TeamController(INETServices service)
        {
            Service = service;

        }

        // GET api/Team
        [ValidateAntiForgeryToken]
        [System.Web.Mvc.Authorize]
        public IEnumerable<Team> GetTeams()
        {
            try
            {
                return Service.GetAllTeams();
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
        }


        // POST api/Team
        public HttpResponseMessage AddTeam(Team team)
        {
            var keyval = Request.GetQueryNameValuePairs().FirstOrDefault();
            if (keyval.Value == null)
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);


            var title = keyval.Value;
            var newTeam = new Team();
            newTeam.Title = title;
            try
            {
                Service.AddTeam(newTeam);
                return Request.CreateResponse(HttpStatusCode.Created, team);

            }
            catch (SystemException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

        }

        // DELETE api/Team/5
        public System.Net.Http.HttpResponseMessage DeleteTeam(int id)
        {

            if (id == 0)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            try
            {
                Service.DeleteTeam(id);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, id);
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}